import {messages} from "share/common";
import React from 'react'
import SearchArea from 'components/search-area';
import {Button, message, Modal, Form, Select} from 'antd'
import bookingManagerService from 'containers/booking-management/booking-manager.service'

const FormItem = Form.Item;
const Option = Select.Option;
import 'styles/booking-management/booking-manager.scss'
import ResizeTable from 'components/resize-table'

class BookingManager extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
      },
      targetBookerOID: '',
      params: {
        name: '',
        businessCode: ''
      },
      data: [],
      modalVisible: false,
      selectedData: [],
      searchForm: [
        {type: "input", id: "businessCode", label: messages('booking-management.key89'/*申请单ID*/)},
        {type: "input", id: "name", label: messages('booking-management.key4'/*申请人*/)}
      ],
      columns: [
        {
          title: messages('booking-management.key90'/*分配状态*/),
          key: "isDeliver",
          dataIndex: "isDeliver",
          render: isDeliver => isDeliver ? <span>{messages('booking-management.key91'/*已分配*/)}</span> :
            <span>{messages('booking-management.key92'/*未分配*/)}</span>
        },
        {
          title: messages('booking-management.key2'/*更新状态*/),
          key: "hasHandled",
          dataIndex: "hasHandled",
          render: hasHandled => hasHandled ? <span>-</span> : <span>{messages('booking-management.key3'/*有更新*/)}</span>
        },
        {
          title: messages('booking-management.key4'/*申请人*/),
          key: "name",
          dataIndex: "name",
        },
        {
          title: messages('booking-management.key5'/*提交日期*/),
          key: "lastModifiedDate",
          dataIndex: "lastModifiedDate",
          render: lastModifiedDate => lastModifiedDate.substr(0, 10)
        },
        {
          title: messages('booking-management.key6'/*申请单号*/),
          key: "businessCode",
          dataIndex: "businessCode",
        },
        {
          title: messages('booking-management.key7'/*类型*/),
          key: "type",
          dataIndex: "type",
          render: record => record === 1001 ?
            <span>{messages('booking-management.key93'/*订票*/)}</span> : record === 1003 ?
              <span>{messages('booking-management.key94'/*退票*/)}</span> :
              <span>{messages('booking-management.key95'/*改签*/)}</span>
        },
        {
          title: messages('booking-management.key96'/*订票专员*/),
          key: "bookerName",
          dataIndex: "bookerName",
        },
        {
          title: messages('booking-management.key8'/*已记录*/),
          key: "hasRecorded",
          dataIndex: "hasRecorded",
        }

      ],
      rowSelection: {
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      transferAccountFetching: false,
      transferAccountOptions: [],
      isOldFunction: true, // 是否不是订票平台
    }
  }

  componentWillMount() {
    bookingManagerService.travelSuppliers().then(res => {
      let isHave = false;
      if (res.data && res.data['2001']) {
        res.data['2001'].map(item => {
          if (item.supplyId === 10051) {
            isHave = true;
          }
        })
        if(isHave){
          this.setState({
            isOldFunction: false,
          }, () => {
            this.getList();
          })
        }else{
          this.getList();
        }
      }
    }).catch(err => {
      message.error(err.response.data.message)
    })
    this.getTransferAccountOptions();
  }

  getList() {
    const {page, pageSize, params, isOldFunction} = this.state;
    this.setState({loading: true});
    params.oldFunction = isOldFunction;
    bookingManagerService.getTraveList(page, pageSize, params)
      .then((response) => {
        this.setState({
          data: response.data,
          loading: false,
          pagination: {
            total: Number(response.headers['x-total-count']) ? Number(response.headers['x-total-count']) : 0,
            onChange: this.onChangePager,
            current: this.state.page + 1
          }
        })
      }).catch((e) => {
      this.setState({loading: false});
    })
  }

  onSelectChange = (selectedRowKeys) => {
    let {rowSelection} = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({rowSelection})
  };

  onSelectItem = (record, selected, selectedRows) => {
    let {selectedData} = this.state;
    if (selected) {
      selectedData.push(record.travelOperationRecordOID)
    } else {
      selectedData.map((item, index) => {
        if (item === record.travelOperationRecordOID) {
          selectedData.splice(index, 1)
        }
      })
    }
    this.setState({selectedData})
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    changeRows.map(changeRow => this.onSelectItem(changeRow, selected));
  };

  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, () => {
        this.getList();
      })
  };
  //点击搜索按钮
  handleSearch = (values) => {
    this.setState({params: values, page: 0}, () => this.getList());
  };

  //点击清空
  handleReset = () => {
    this.setState({
      params: {
        name: '',
        businessCode: ''
      },
      page: 0,
    }, () => this.getList())
  };

  //分配订票任务
  handleModalOk = () => {
    let {selectedData, rowSelection} = this.state;

    let values = {
      "travelOperationRecordOIDs": selectedData,
      "excludedTravelOperationRecordOIDs": [],
      "businessCodes": [],
      "name": null
    };
    this.setState({loading: true});
    bookingManagerService.deliveryTicket(this.state.targetBookerOID, values).then(response => {
      if (response.status === 200) {
        rowSelection.selectedRowKeys = [];
        this.setState({loading: false, rowSelection, selectedData: []});
        message.success(messages('booking-management.key108', {
          arg1: (response.data.successNum + ''),
          arg2: (response.data.failNum + '')
        }/*成功:{arg1}条，失败:{arg2}条*/));
        this.handleModalCancel()
      }
    }).catch(() => {
      message.error(messages('booking-management.key97'/*保存失败*/));
      this.handleModalCancel();
      this.setState({loading: false})
    })
  };

  //分配时弹窗打开
  delivery = () => {
    this.setState({modalVisible: true})
  };

  //弹窗关闭
  handleModalCancel = () => {
    this.getList();
    this.setState({modalVisible: false})
  };

  //获取转移人值列表
  getTransferAccountOptions = () => {
    if (this.state.transferAccountOptions && this.state.transferAccountOptions.length) {
      return;
    }
    this.setState({transferAccountFetching: true})
    bookingManagerService.getTransferPersons().then(response => {
      response.status === 200 && this.setState({
        transferAccountOptions: response.data,
        transferAccountFetching: false
      });
    }).catch(() => {
      this.setState({transferAccountFetching: false})
    })
  };

  handleSelectChange = (value) => {
    this.setState({targetBookerOID: value})
  };

  render() {

    const {getFieldDecorator} = this.props.form;
    const {columns, data, searchForm, rowSelection, pagination, modalVisible, transferAccountOptions, loading, selectedData} = this.state;
    return (
      <div className="booking-manager">
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.handleSearch}
          clearHandle={this.handleReset}
        />
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total', {total: `${pagination.total}`})}
          </div>
        </div>
        <div className="table-header-buttons">
          <Button
            type="primary"
            onClick={this.delivery}
            disabled={selectedData.length <= 0}
          >
            {messages('booking-management.key98'/*分配订票任务*/)}
          </Button>
          <span style={{marginLeft: "1rem"}}>
            {messages('common.total.selected', {total: `${selectedData.length}`})}
          </span>
        </div>
        <div className="booking-manager-table">
          <ResizeTable
            loading={loading}
            pagination={pagination}
            rowSelection={rowSelection}
            dataSource={data}
            columns={columns}
            size="middle"
            rowKey={record => record.id}
            bordered
          />
        </div>
        <Modal
          title={messages('booking-management.key99'/*转移订票任务*/)}
          visible={modalVisible}
          okText={messages('common.ok')}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}
          width="600px"
        >
          <div>{messages('booking-management.key109', {arg1: selectedData.length}/*将{arg1}条任务转移给...*/)}</div>
          <Form>
            <FormItem>
              {getFieldDecorator('transferAccount', {
                rules: [{
                  required: true,
                  message: messages('common.please.select')
                }],
              })(
                <Select placeholder={messages('common.please.select')}
                        onChange={this.handleSelectChange}>
                  {transferAccountOptions.map(option => <Option key={option.userOID}>{option.fullName}</Option>)}
                </Select>
              )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}


const wrappedBookingManagerDetail = Form.create()(BookingManager);

export default wrappedBookingManagerDetail;

